#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Creaet Time    : 2022/12/5 14:30
# @File           : download_video.py
# @IDE            : PyCharm
# @desc           : 简要说明

import datetime
from urllib.parse import urlparse
import requests, os, re
from settings import RESOURCES_DIR, HEADERS


class DownloadVideo:
    """
    根据视频id下载视频
    """

    VIDEO_DETAIL_API = "https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/"

    def __init__(self, aweme_id: str = None, share_string: str = None):
        """
        :param aweme_id: 视频 ID
        :param share_string: 视频分享链接，也可以通过这个解析出视频 ID
        """
        self.video_link = None
        self.save_dir = None
        self.headers = HEADERS
        if share_string:
            self.aweme_id = self.parse_link(share_string)
        else:
            self.aweme_id = aweme_id

    def parse_link(self, share_string) -> str:
        """
        解析视频分享链接
        :param share_string:
        :return:
        """
        share_link = re.findall('[a-z]+://[\S]+', share_string, re.I | re.M)[0]
        start_page = requests.get(url=share_link, headers=self.headers)
        url = urlparse(start_page.url)
        return url.path.split("/")[-2]

    def get_video_detail(self) -> dict:
        """
        获取视频信息

        :return:
        """
        params = {
            "item_ids": self.aweme_id
        }
        return requests.get(url=self.VIDEO_DETAIL_API, headers=self.headers, params=params).json()

    def mkdir(self):
        """
        创建存储目录

        :return:
        """
        info = self.get_video_detail()
        if len(info['item_list']) < 1:
            print("info", info)
            raise ValueError("未获取到视频地址")
        self.video_link = info['item_list'][0]['video']['play_addr']['url_list'][0]
        print("视频链接：", self.video_link)
        self.save_dir = os.path.join(RESOURCES_DIR, datetime.datetime.now().strftime("%Y%m%d"))
        if not os.path.exists(self.save_dir):
            os.mkdir(self.save_dir)

    def download_video(self):
        """
        下载视频
        :return:
        """
        with open(os.path.join(self.save_dir, f"{self.aweme_id}.mp4"), 'wb') as v:
            try:
                v.write(requests.get(url=self.video_link, headers=self.headers).content)
            except Exception as e:
                print('下载失败', e)

    def run(self):
        """
        开始下载用户下视频
        :return:
        """
        self.mkdir()
        self.download_video()
